package org.example.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.config.JwtConfig;
import org.example.exception.NotLoginException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@Slf4j
public class IsLoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始校验用户是否登陆");
        // 1. 获取到用户携带的token
        String token = request.getHeader("token");
        log.info("1.token:{}", token);
        if (token == null) {
            throw new NotLoginException("用户没有登陆");
        }
        // 2. 验证token
        boolean b = JwtConfig.checkToken(token);
        log.info("2.b:{}", b);
        if(!b){
            throw new NotLoginException("用户没有登陆");
        }
        // 3. 校验认证一致
        Claims claims = JwtConfig.parseJWT(token);
        String id = claims.get("id").toString();
        log.info("3.id:{}", id);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String redisToken = ops.get("token:" + id);
        log.info("4.redisToken:{}", redisToken);
        if(!token.equals(redisToken)){
            throw new NotLoginException("用户没有登陆");
        }
        return true;
    }
}
